<!DOCTYPE html>
<html>
<head>
    <title>WorkTool WebSocket Client</title>
    <script>
        let ws = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        let heartbeatTimer = null;
        
        const wsUrl = `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/robot/connect`;

        function connect() {
            let deviceId = document.getElementById('deviceId').value;
            if (!deviceId) {
                alert('请输入设备ID');
                return;
            }

            try {
                ws = new WebSocket(`${wsUrl}?robotId=${deviceId}`);
                
                ws.onopen = function() {
                    console.log('Connected');
                    reconnectAttempts = 0; // 重置重连次数
                    
                    // 发送连接消息
                    ws.send(JSON.stringify({
                        socketType: 2,
                        list: [{
                            type: 301,
                            log: `连接建立: ${deviceId} appVersion: 3.6.2.2 Android Test Device workVersion: 4.1.31 deviceRooted: false hook: false appName: WT Pro`
                        }]
                    }));

                    // 连接成功后启动心跳
                    startHeartbeat();
                };
                
                ws.onmessage = function(evt) {
                    console.log('Received:', evt.data);
                    const log = document.getElementById('log');
                    try {
                        const data = JSON.parse(evt.data);
                        let message = '';
                        let messageClass = '';
                        
                        // 处理新的消息格式
                        if (data.code !== undefined) {
                            messageClass = data.code === 200 ? 'success-message' : 'error-message';
                            message = `Code: ${data.code}, Message: ${data.message}`;
                            if (data.data) {
                                message += `, Data: ${data.data}`;
                            }
                        } else {
                            message = evt.data;
                            messageClass = 'info-message';
                        }
                        
                        log.innerHTML += `
                            <div class="${messageClass}">
                                <span class="timestamp">${new Date().toLocaleString()}</span>
                                ${message}
                            </div>`;
                    } catch (e) {
                        log.innerHTML += `
                            <div class="error-message">
                                <span class="timestamp">${new Date().toLocaleString()}</span>
                                ${evt.data}
                            </div>`;
                    }
                    log.scrollTop = log.scrollHeight;
                };
                
                ws.onclose = function() {
                    console.log('Disconnected');
                    stopHeartbeat(); // 断开连接时停止心跳

                    if (reconnectAttempts < maxReconnectAttempts) {
                        reconnectAttempts++;
                        console.log(`Reconnecting... Attempt ${reconnectAttempts}`);
                        setTimeout(connect, 1000 * reconnectAttempts);
                    } else {
                        console.log('Max reconnection attempts reached');
                    }
                };
                
                ws.onerror = function(err) {
                    console.error('WebSocket error:', err);
                    const log = document.getElementById('log');
                    log.innerHTML += '<div style="color: red;">' + new Date().toLocaleString() + ': Error: ' + err.type + '</div>';
                    log.scrollTop = log.scrollHeight;
                };
            } catch (err) {
                console.error('Connection error:', err);
                const log = document.getElementById('log');
                log.innerHTML += '<div style="color: red;">' + new Date().toLocaleString() + ': Connection error: ' + err + '</div>';
                log.scrollTop = log.scrollHeight;
            }
        }

        function disconnect() {
            if (ws) {
                reconnectAttempts = maxReconnectAttempts; // 防止自动重连
                stopHeartbeat(); // 停止心跳
                ws.close();
                ws = null;
            }
        }

        // 添加心跳检测
        function startHeartbeat() {
            stopHeartbeat(); // 先停止现有心跳
            heartbeatTimer = setInterval(() => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    try {
                        ws.send(JSON.stringify({
                            type: 11,
                            code: 0,
                            msg: "ping",
                            success: true,
                            timestamp: Date.now()
                        }));
                        console.log('Heartbeat sent');
                    } catch (err) {
                        console.error('Heartbeat error:', err);
                        stopHeartbeat();
                    }
                }
            }, 30000);
        }

        // 停止心跳
        function stopHeartbeat() {
            if (heartbeatTimer) {
                clearInterval(heartbeatTimer);
                heartbeatTimer = null;
            }
        }

        // 清空日志
        function clearLog() {
            const log = document.getElementById('log');
            log.innerHTML = '';
        }
    </script>
    <style>
        .container {
            margin: 20px;
            font-family: Arial, sans-serif;
        }
        .controls {
            margin-bottom: 20px;
        }
        .log {
            border: 1px solid #ccc;
            padding: 10px;
            height: 400px;
            overflow-y: auto;
            background: #f5f5f5;
            font-family: monospace;
        }
        button {
            margin-right: 10px;
            padding: 5px 10px;
        }
        input {
            padding: 5px;
            width: 300px;
            margin-right: 10px;
        }
        .success-message {
            color: #28a745;
            background-color: #f8fff9;
            border-left: 4px solid #28a745;
            padding: 8px 12px;
            margin: 4px 0;
        }
        .error-message {
            color: #dc3545;
            background-color: #fff8f8;
            border-left: 4px solid #dc3545;
            padding: 8px 12px;
            margin: 4px 0;
        }
        .info-message {
            color: #17a2b8;
            background-color: #f8fdff;
            border-left: 4px solid #17a2b8;
            padding: 8px 12px;
            margin: 4px 0;
        }
        .log div {
            font-size: 14px;
            line-height: 1.4;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .log div:hover {
            background-color: rgba(0,0,0,0.02);
        }
        .controls button {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 16px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .controls button:hover {
            background-color: #0056b3;
        }
        .controls button:active {
            background-color: #004085;
        }
        .controls input {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 8px;
            font-size: 14px;
        }
        .controls input:focus {
            outline: none;
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        .timestamp {
            color: #666;
            font-size: 12px;
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>WorkTool WebSocket Client</h2>
        <div class="controls">
            <input type="text" id="deviceId" placeholder="32-char device ID" value="wtd1k5lm8q1eh0ijeq7gy3n9sl23cf1y">
            <button onclick="connect()">Connect</button>
            <button onclick="disconnect()">Disconnect</button>
            <button onclick="clearLog()">Clear Log</button>
        </div>
        <div id="log" class="log"></div>
    </div>
</body>
</html>